package com.gec.controller;

import com.gec.model.system.SysUser;
import com.gec.model.vo.LoginVo;
import com.gec.service.SysUserService;
import com.gec.system.exception.MyCustomerException;
import com.gec.system.util.JwtHelper;
import com.gec.system.util.MD5Helper;
import com.gec.system.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "菜单管理控制器")
@RestController
@RequestMapping(value = "/admin/system/index")
public class SysLoginController {
    @Autowired
    private SysUserService sysUserService;

    /**登录接口*/
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        System.out.println("loginVo.getPassword():"+loginVo.getPassword());
        //1.根据userName查询数据
        SysUser sysUser=this.sysUserService.getUserInfoUserName(loginVo.getUsername());
        //2.判断用户是否存在
        if(sysUser == null){
            throw new MyCustomerException(20001,"用户不存在");
        }
        //3.判断密码是否正确
        //从loginVo获取密码，然后进行加密
        String password=loginVo.getPassword();
        String passwordMD5 = MD5Helper.encrypt(password);
        //判断数据库里的密码是否和前端传来的加密密码相同
        if(!sysUser.getPassword().equals(passwordMD5)){
            throw new MyCustomerException(20001,"密码不正确");
        }
        //4.判断状态
        if(sysUser.getStatus().longValue()==0){
            throw new MyCustomerException(20001,"账号已停用");
        }
        Map<String,Object>map=new HashMap<>();
        //获取token
        String token=JwtHelper.createToken(sysUser.getId()+"",sysUser.getUsername());
        map.put("token",token);
        return Result.ok(map);
    }

    /**获取用户信息*/
    @GetMapping(value = "/info")
    public Result info(HttpServletRequest request){
        //获取请求头的token
        String token=request.getHeader("token");
        //根据token获取username用户名称
        String username=JwtHelper.getUsername(token);
        //根据用户名称来获取用户信息
        Map<String,Object> map=sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    /**退出登录*/
    @GetMapping("/logout")
    public Result logout(){
        return Result.ok();
    }
}
